import React from 'react';

export default class Todo extends React.Component {
  constructor() {
    super();
    this.state = {
      value: '',
      todos: []
    }
  }
  render() {
    return (
      <div>
        <input type="text"
               value = {this.state.value}
               onChange = {this.changeValue.bind(this)}
               onKeyUp = {this.addTodo.bind(this)}/>
        <ul>
          {this.state.todos.map((item, index) => {
            return <li key={index} onClick={this.deleteTodo.bind(this,index)}>{item.text}</li>
          })}
        </ul>
      </div>
    )
  }
  changeValue(e) {
    this.setState({value: e.target.value})
  }
  addTodo(e) {
    const value = this.state.value;
    if (e.keyCode === 13 && value.trim()) {
      // 提交并清空数据
      console.log(this.state.todos)
      this.state.todos.push({
        text: value
      });
      console.log(this.state.todos)
      this.setState({value: ''});
    }
  }
  deleteTodo(index, e) {
    const list = this.state.todos;
    list.splice(index, 1)
    this.setState({todos: list});
  }
}